//
//  CQCommon.m
//  CQUtils
//
//  Created by Martin on 16/5/17.
//  Copyright © 2016年 com.runo. All rights reserved.
//

#import "CQCommon.h"
#import <AudioToolbox/AudioToolbox.h>
#import <SystemConfiguration/SCNetworkReachability.h>
#import "NSDate+CQDate.h"
#import "CQCommonHeader.h"

@implementation CQCommon

+ (void)cqShake:(int)time withDelta:(CGFloat)delta addSpeed:(NSTimeInterval)interval withCurrent:(NSInteger)current withDirection:(int)direction withTarget:(UIView*)view isShake:(BOOL)shake
{

    [UIView animateWithDuration:interval animations:^{
        view.transform = CGAffineTransformMakeTranslation(delta*direction, 0.0f);
    } completion:^(BOOL finished) {
        if (current >= time) {
            view.transform = CGAffineTransformIdentity;
            if (shake) {
                AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);//调用手机震动
            }
            return ;
        }
        [CQCommon cqShake:(time - 1)
                     withDelta:delta
                      addSpeed:interval
                   withCurrent:current + 1
                 withDirection:direction*-1
                    withTarget:view isShake:shake];
    }];
    
}

+(void)cqShakeView:(UIView *)view{
    [CQCommon cqShake:4 withDelta:5 addSpeed:0.05 withCurrent:0 withDirection:5 withTarget:view isShake:NO];
}

+(BOOL)cqIsConnectNetwork{
    
    //创建零地址，0.0.0.0的地址表示查询本机的网络连接状态
    struct sockaddr_storage zeroAddress;
    bzero(&zeroAddress, sizeof(zeroAddress));
    zeroAddress.ss_len = sizeof(zeroAddress);
    zeroAddress.ss_family = AF_INET;
    
    SCNetworkReachabilityRef ref =SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr*)&zeroAddress);
    SCNetworkReachabilityFlags flags;
    
    //获得连接标示
    BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(ref, &flags);
    CFRelease(ref);
    
    if (!didRetrieveFlags) {
        return NO;
    }
    
    BOOL isReachable = flags & kSCNetworkFlagsReachable;
    BOOL needsConnection = flags & kSCNetworkFlagsConnectionRequired;
    
    return  (isReachable && !needsConnection) ? YES:NO;
    
}

+(NSString *)cqGetNetworkStatus
{
    return nil;
}

+(void)cqNetworkStatusListener:(CQNetStatusListener)listener{
    //网络管理单列
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    //设置监听回调
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {

        NSString *result = nil;
        switch (status) {
            case AFNetworkReachabilityStatusUnknown:
                result = @"UNKNOW";
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi:
                result = @"WIFI";
                break;
            case AFNetworkReachabilityStatusReachableViaWWAN:
                result = @"WAN";
                break;
            case AFNetworkReachabilityStatusNotReachable:
                result = @"NotReachable";
                break;
            default:
                break;
        }
        listener(result);
    }];
    //开始监听
    [manager startMonitoring];
}

+(void)cqShowWarningMessage:(NSString *)message{
    UIAlertView* alertView=[[UIAlertView alloc] initWithTitle:@"警告" message:message delegate:nil  cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alertView show];
}

+(void)cqShowYesOrNoAlert:(UIViewController *)vc Title:(NSString *)title Message:(NSString *)message Yes:(void (a^)(void))yesBlock No:(void (^)(void))noBlock{
    
    UIAlertController *control = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *yesAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if (yesBlock != nil) {
            yesBlock();
        }
    }];
    UIAlertAction *noAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if(noBlock != nil){
            noBlock();
        }
    }];
    [control addAction:yesAction];
    [control addAction:noAction];
    [vc presentViewController:control animated:YES completion:nil];
}

+(void)cqShowTipsAlert:(NSString *)message{
    UIAlertView* alertView=[[UIAlertView alloc] initWithTitle:@"提示" message:message delegate:nil  cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alertView show];
}

+(void)shareWriteFile:(NSString *)message Filename:(NSString *)name
{
    NSFileManager * fileManger;
    NSFileHandle * fileHandle;
    @try {
        NSArray * arr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString * path = arr[0];
        NSString * filePath = [path stringByAppendingPathComponent:name];
        NSLog(@"filePath:%@",filePath);
        fileManger=[NSFileManager defaultManager];
        if (![fileManger fileExistsAtPath:filePath]) {
            BOOL flag= [fileManger createFileAtPath:filePath contents:nil attributes:nil];
            if (!flag) {
                @throw [[NSException alloc] initWithName:@"创建文件失败" reason:@"创建文件失败" userInfo:nil];
            }
        }
        fileHandle=[NSFileHandle fileHandleForUpdatingAtPath:filePath];
        NSData * data=[fileHandle availableData];
        NSUInteger length=data.length;
        [fileHandle seekToFileOffset:length];
        
        NSString * dateStr=[NSDate cqNowString];
        NSString * messageInfo=[NSString stringWithFormat:@"%@ -- %@\n",dateStr,message];
        
        NSData * messageData=[messageInfo dataUsingEncoding:NSUTF8StringEncoding];
        [fileHandle writeData:messageData];
        
    }
    @catch (NSException *exception) {
        NSLog(@"exception:%@",exception.description);
    }
    @finally {
        if (fileHandle!=nil) {
            [fileHandle closeFile];
        }
    }
    
}

//  隐藏电池栏
//  新版的只要viewController继承了CQBaseViewController里面就会有cqHidenSatusBar属性，在push之前设置好就行
+(void)cqSetStatusBarHidden:(BOOL)isHide
{
    [[UIApplication sharedApplication] setStatusBarHidden:isHide];
}

//  设置电池状态栏为默认样式 黑字
//一样，在BaseViewController里面有
+(void)cqSetStatusBarStyleDefault
{
    if(ISIOS7)
    {
        [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
    }
}

//设置电池状态栏为高亮样式 白字
+(void)cqSetStatusBarStyleLightContent
{
    if(ISIOS7)
    {
        [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    }
}

+(NSString *)cqGetLibraryPath{
    
    NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,NSUserDomainMask,YES) objectAtIndex:0];
    
    return filePath;
}

+(NSString *)cqGetCQCacheDirectoryPath{
    
    NSString *dbFile = [[CQCommon cqGetLibraryPath] stringByAppendingPathComponent:@"cqCache"];
    BOOL isDirectory = false;
    BOOL isExist = [[NSFileManager defaultManager] fileExistsAtPath:dbFile isDirectory:&isDirectory];
    
    if (isExist == NO || !isDirectory) {
      
        if ([CQCommon cqCreateDirectory:dbFile]){
            return dbFile;
        }else{
            return nil;
        }
        
    }
    return dbFile;
    
}

+(NSString *)cqGetDBPath{
    
    if ([CQCommon cqGetCQCacheDirectoryPath] != nil) {
        
        NSString *dbPath = [[CQCommon cqGetCQCacheDirectoryPath] stringByAppendingPathComponent:@"finance.sqlite"];
        BOOL isDirectory = false;
        BOOL isExist = [[NSFileManager defaultManager] fileExistsAtPath:dbPath isDirectory:&isDirectory];
        
        if (isExist == NO || isDirectory) {
            
            if ([CQCommon cqCreateFile:dbPath]){
                return dbPath;
            }else{
                return nil;
            }
            
        }
        return dbPath;
        
    }else{
        kLog(@"获取数据库文件失败");
        return nil;
    }
    
}

+(BOOL)cqCreateDirectory:(NSString *)directoryPath{
    
    NSError *error = nil;
   BOOL result = [[NSFileManager defaultManager]createDirectoryAtPath:directoryPath withIntermediateDirectories:YES attributes:nil error:&error];
    
    if (error != nil) {
        kLog(error);
        kLog(@"创建文件夹失败");
    }
    return result;
}

+(BOOL)cqCreateFile:(NSString *)filePath{
    
    BOOL result = [[NSFileManager defaultManager]createFileAtPath:filePath contents:nil attributes:nil];;
    if (!result) {
        kLog(@"创建数据库文件失败");
    }
    return result;
}

/**hex颜色转化成UIcolor*/
+(UIColor *)cqColorForHexString:(NSString *)hexStr{
    
    hexStr = [hexStr stringByReplacingOccurrencesOfString:@"#" withString:@""];
    NSInteger hexColor = strtoul([hexStr UTF8String], 0, 16);
    float red = ((float)((hexColor & 0xFF0000) >> 16));
    float green = ((float)((hexColor & 0xFF00) >> 8));
    float blue = ((float)(hexColor & 0xFF));
    return kCustomerColor(red, green, blue);
}
+(UIColor *)cqColorForHexString:(NSString *)hexStr Alpha:(CGFloat)alpha{
    hexStr = [hexStr stringByReplacingOccurrencesOfString:@"#" withString:@""];
    NSInteger hexColor = strtoul([hexStr UTF8String], 0, 16);
    float red = ((float)((hexColor & 0xFF0000) >> 16));
    float green = ((float)((hexColor & 0xFF00) >> 8));
    float blue = ((float)(hexColor & 0xFF));
    return kCustomerColorAlpha(red, green, blue,alpha);
}

+(NSString *)cqGetSerialNumberString:(NSString *)numberStr{
    
    
    NSMutableString *mstr = [NSMutableString stringWithString:numberStr];

    NSRange dotRange = [numberStr rangeOfString:@"."];
    NSInteger startIndex = mstr.length-1;
    if (dotRange.location != NSNotFound) {
        startIndex = dotRange.location-1;
    }
    NSInteger count = 0;
    while (startIndex) {
        count++;
        if (count==3) {
            
            [mstr insertString:@"," atIndex:startIndex];
            count = 0;
        }
        
        startIndex--;
    }
    return mstr;
}

@end
